package com.edgclub.edg.http;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.http.param.Params;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 网络请求的服务
 * 
 * @author 陈坤彬
 *
 */
public class VolleyHttp {

	private RequestQueue mRequestQueue;
	private Context context;

	// 用来管理所有的请求的线程
	private ArrayList<String> tags = new ArrayList<String>();

	public VolleyHttp(Context context) {
		this.context = GuZhiApplication.getInstance();

//		if (context instanceof Activity) {
//			mRequestQueue = ((GuZhiApplication) ((Activity) context)
//					.getApplication()).mRequestQueue;
//		} else if (context instanceof Service) {
//			mRequestQueue = ((GuZhiApplication) ((Service) context)
//					.getApplication()).mRequestQueue;
//		}else{
			mRequestQueue = GuZhiApplication.getInstance().mRequestQueue;
//		}
	}

	/**
	 * post请求
	 * 
	 * @param tag
	 *            请求的标识
	 * @param url
	 *            请求的链接
	 * @param params
	 *            请求的参数{@link Params}
	 * @param listener
	 *            请求的回调 不能为空{@link VolleyListener}
	 */
	public void post(final String tag, String url, final Params params,
					 final VolleyListener listener) {

		if (listener == null) {
			throw new NullPointerException("must set a listener to this post");
		}

		showUrl(url, params);
		StringRequest request = new StringRequest(Method.POST, url,
				new Response.Listener<String>() {

					@Override
					public void onResponse(String response) {
						Log.d("response:", response);
						listener.onSuccess(response,tag);
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						listener.onFaile(error,tag);
					}
				}) {

			@Override
			public Map<String, String> getHeaders() throws AuthFailureError {
				Map<String, String> headers = new HashMap<String, String>();
				headers.put("Charset", "UTF-8");
				headers.put("gzVersion", getVersion(context));
				headers.put("device", "android " + android.os.Build.VERSION.RELEASE);
				headers.put("model", android.os.Build.MODEL);
				headers.put("userId", GuZhiApplication.getInstance().getUserId());
				// headers.put("Content-Type", "application/x-javascript");
//				headers.put("Accept-Encoding", "gzip,deflate");
				headers.put("Device-Agent", GuZhiApplication.getInstance().getImei());
				headers.put("token", GuZhiApplication.getInstance().getToken());
				return headers;
			}

			// 设置请求的参数
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {

				return params.getParams();
			}

			// 设置超时时间
			@Override
			public RetryPolicy getRetryPolicy() {
				return new DefaultRetryPolicy(50000,
						1,
						1);
			}

			@Override
			protected Response<String> parseNetworkResponse(
					NetworkResponse response) {
				// TODO Auto-generated method stub
				return super.parseNetworkResponse(response);
			}

		};

		// // 如果未停止
		// if (!request.isCanceled()) {
		// request.cancel();
		// }
		// 设置标签 ,方便停止
		request.setTag(tag);
		tags.add(tag);
		// 添加到请求队列之中
		listener.onStart(tag);
		mRequestQueue.add(request);

	}
	
	/**
	 * post请求
	 *
	 * @param tag
	 *            请求的标识
	 * @param url
	 *            请求的链接
	 * @param params
	 *            请求的参数{@link Params}
	 * @param listener
	 *            请求的回调 不能为空{@link VolleyListener}
	 */
	public void postCharge(final String tag, String url, final Params params,
						   final VolleyListener listener) {

		if (listener == null) {
			throw new NullPointerException("must set a listener to this post");
		}

		showUrl(url, params);
		StringRequest request = new StringRequest(Method.POST, url,
				new Response.Listener<String>() {

					@Override
					public void onResponse(String response) {
						Log.d("response:", response);
						listener.onSuccess(response,tag);
					}
				}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				listener.onFaile(error,tag);
			}
		}) {

			@Override
			public Map<String, String> getHeaders() throws AuthFailureError {
				Map<String, String> headers = new HashMap<String, String>();
				headers.put("Charset", "UTF-8");
				headers.put("gzVersion", getVersion(context));
				headers.put("device", "android " + android.os.Build.VERSION.RELEASE);
				headers.put("model", android.os.Build.MODEL);
				headers.put("userId", GuZhiApplication.getInstance().getUserId());
				headers.put("Device-Agent", GuZhiApplication.getInstance().getImei());
				headers.put("token", GuZhiApplication.getInstance().getToken());
				// headers.put("Content-Type", "application/x-javascript");
//				 headers.put("Accept-Encoding", "gzip,deflate");
				return headers;
			}

			// 设置请求的参数
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {

				return params.getParams();
			}

			// 设置超时时间
			@Override
			public RetryPolicy getRetryPolicy() {
				return new DefaultRetryPolicy(50000,
						1,
						1);
			}

			@Override
			protected Response<String> parseNetworkResponse(
					NetworkResponse response) {
				// TODO Auto-generated method stub
				return super.parseNetworkResponse(response);
			}

		};

		// // 如果未停止
		// if (!request.isCanceled()) {
		// request.cancel();
		// }
		// 设置标签 ,方便停止
		request.setTag(tag);
		tags.add(tag);
		// 添加到请求队列之中
		listener.onStart(tag);
		mRequestQueue.add(request);

	}
	
	

	/**
	 * get请求
	 * 
	 * @param tag
	 * @param url
	 * @param listener
	 */
	public void get(final String tag, String url, final VolleyListener listener) {
		StringRequest request = new StringRequest(Method.GET, url,
				new Response.Listener<String>() {

					@Override
					public void onResponse(String response) {
						listener.onSuccess(response,tag);
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {

						listener.onFaile(error,tag);
					}
				});

		request.setTag(tag);
		tags.add(tag);
		mRequestQueue.add(request);
	}

	/**
	 * 取消请求
	 * 
	 * @param tag
	 */
	public void cancel(String tag) {
		if (tags.contains(tag)) {
			mRequestQueue.cancelAll(tag);
			tags.remove(tag);
		}
	}

	/**
	 * 取消全部的请求,相当于停止线程池
	 */
	public void cancelAll() {
		for (String tag : tags) {
			mRequestQueue.cancelAll(tag);
		}
	}
	
	/**
	 * 打印测试链接
	 * @param url
	 * @param params
	 */
	private void showUrl(String url , Params params){
		StringBuilder sb = null ;
		if(params !=null){
			sb = new StringBuilder(url+"?");
			for(TreeMap.Entry<String, String> entry : params.getParams().entrySet()){
				try {
					sb.append(entry.getKey())
					.append('=')
					.append(URLEncoder.encode(entry.getValue(), "UTF-8"))
					.append('&');
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			sb.deleteCharAt(sb.length() - 1);
		}
		if (sb != null){
			Log.d("url:", sb.toString());
		}
	}
	
	//获取版本号
	public  String getVersion(Context context)  {  
        try {  
            PackageInfo pi=context.getPackageManager().getPackageInfo(context.getPackageName(), 0);  
            return pi.versionName;  
        } catch (NameNotFoundException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }
		return "";  
    }
}
